package cn.yunzhisheng.phone;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Parcelable;
import android.util.Log;

public class SyncContactReceiver extends BroadcastReceiver {
	private static final String TAG = "BlueToothReceiver";
	private static final String BLUETOOTH_SYNC_SUCCESS_ACTION = "android.intent.action.BLUETOOTH_SYNC_SUCCESS";
	private Context mContext;

	public void onReceive(Context context, Intent intent) {
		mContext = context;
		String action = intent.getAction();
		ArrayList<Parcelable> phonebook = intent.getParcelableArrayListExtra("phonebook");

		if (action.equals(BLUETOOTH_SYNC_SUCCESS_ACTION)) {
			Log.d(TAG, "android.intent.action.BLUETOOTH_SYNC_SUCCESS");
			if(null != phonebook && phonebook.size() > 0){
				for (int i = 0; i < phonebook.size(); i++) {
					Log.d(TAG, "phonebook = " + phonebook.get(i));
					String number = ((HashMap)phonebook.get(i)).get("ItemNumber").toString();
			        String name = ((HashMap)phonebook.get(i)).get("ItemName").toString();
			        insertContact(name, number);
				}
			}else{
				Log.d(TAG, "phoneBook = null");
			}
		}
	}

	private void insertContact(String name, String number) {
		ContentResolver resolver = mContext.getContentResolver();
		Uri uri = Uri.parse("content://cn.yunzhisheng.vui.provider.ContactProvider/contact");
		ContentValues values = new ContentValues();
		values.put("display_name", name);
		values.put("has_phone_number", 1);
		Uri resultUri = resolver.insert(uri, values);
		if (resultUri != null) {
			List<String> segments = resultUri.getPathSegments();
			if (segments != null && segments.size() > 0) {
				String contactId = segments.get(1);
				insertPhone(Long.parseLong(contactId), number);
			}
		}
	}

	private void insertPhone(long contactId, String number) {
		ContentResolver resolver = mContext.getContentResolver();
		Uri uri = Uri.parse("content://cn.yunzhisheng.vui.provider.ContactProvider/phone");
		ContentValues values = new ContentValues();
		values.put("contact_id", contactId);
		values.put("raw_number", number);
		values.put("number", number);
		resolver.insert(uri, values);
	}

}
